﻿/*

Copyright (c) 2009, Stephen Remde
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY STEPHEN REMDE ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL STEPHEN REMDE BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Graphs;
using WikiMiner;
using System.Drawing;

namespace WindowsFormsApplication1
{
    class SearchContext
    {
        public Article From { get; protected set; }
        public Article To { get; protected set; }

        protected List<Candidate> open = new List<Candidate>();
        protected List<Article> closed = new List<Article>();


        public SearchContext(Article from, Article to, float relAdd, float relLink) 
            : this(from, to)
        {
            this.relAdd = relAdd;
            this.relLink = relLink;

            Graph = new Graph();

            Node n = new WikiVisNode()
            {
                text = From.title,
                fixedinplace = true,
                h = Relatedness.Get(from.title, to.title)
            };

            Graph.AddNode(n);
        }

        public SearchContext(Article from, Article to)
        {
            this.From = from;
            this.To = to;

            open.Add(new Candidate() { article = From, destination = to, parent = null });         
          
        }
        protected SearchContext()
        {
        }

        public float relAdd { get; set; }
        public float relLink { get; set; }


        public int Iterations { get; protected set; }
        public Graph Graph { get; protected set; }
        public Article[] Path { get; protected set; }
        public bool Compelete { get; set; }

        public void AutoStep(float seconds)
        {
        }

        public bool Step()
        {
            if (Compelete)
                return true;

            if (open.Count == 0)
                return Compelete = true;

            Iterations++;

            Candidate at = open.OrderBy(item => item.f).First();


            {
                List<Article> path = new List<Article>();

                for (var p = at; p != null; p = p.parent)
                    path.Add(p.article);

                path.Reverse();

                this.Path = path.ToArray();
            }


            closed.Add(at.article);
            open.Remove(at);

            

            Node node_at = null;
            Graph g = Graph;

            if (g != null)
            {
                Recolour();

                node_at = g.GetNode(at.article.title);

                node_at.visible = true;

                if (at.parent != null)
                {
                    g.GetLink(node_at, g.GetNode(at.parent.article.title)).visible = true;

                }

                Candidate at2 = at;

                while (at2 != null)
                {
                    g.GetNode(at2.article.title).color = Color.Salmon;

                    if (at.parent != null)
                        g.GetLink(g.GetNode(at.article.title), g.GetNode(at.parent.article.title)).color = Color.Red;

                    at2 = at2.parent;
                }
            }

            if (at.article.title != To.title)
            {
                foreach (var link in Links.GetOutLinks(at.article.id, To.id))
                {
                    float rel = Relatedness.Get(at.article.title, link.title);

                    Node node_to = null;

                    if (g != null)
                    {
                        node_to = g.GetNode(link.title);

                        if (node_to == null)
                        {
                            node_to = new WikiVisNode() { text = link.title, visible = false };
                            g.AddNode(node_to, node_at);
                        }

                        if (rel > relAdd)
                            node_to.visible = true;

                        Link l = g.AddLink(new WikiVisLink() { a = node_at, b = node_to, visible = false, rel = rel });

                        l.AddArrowTo(node_to);
                        //l.text = rel.ToString("0%");
                        l.width = 10 * rel;

                        if (rel > relLink)
                        {
                            l.visible = true;
                        }
                    }

                    if (!closed.Exists(item => item.id == link.id))
                    {
                        Candidate existing = open.FirstOrDefault(item => item.article.id == link.id);

                        if (existing != null)
                        {
                            existing.UpdateParentIfBetter(at);
                        }
                        else
                        {
                            existing = new Candidate()
                            {
                                article = link,
                                parent = at
                            };
                            open.Add(existing);
                        }

                        if (g != null)
                        {
                            (node_to as WikiVisNode).g = existing.G;
                            (node_to as WikiVisNode).h = existing.H;
                        }
                    }
                }
            }
            else
            {
                return Compelete = true;
            }

            return false;
        }



        public class WikiVisNode : Node
        {
            public float g;
            public float h;
        }

        public class WikiVisLink : Link
        {
            public float rel;
        }

        public bool ColorToDestination { get { return !ColorFromStart; } set { ColorFromStart = !value; } }
        public bool ColorFromStart { get; set; }
        public bool ShowTextOnLinks { get; set; }
        public bool ColorCurrentPath { get; set; }
        
        private void Recolour()
        {

            float maxg = 1;
            if (ColorFromStart)
            {
                foreach (var n in Graph.GetNodes())
                {
                    float t = (n as WikiVisNode).g;

                    if (t > maxg)
                        maxg = t;
                }
            }
            foreach (var n in Graph.GetNodes())
            {
                float t = ColorFromStart ? (n as WikiVisNode).g : (n as WikiVisNode).h;
                int gg = (int)(255 * t / maxg);
                if (gg > 255) gg = 255;
                n.color = Color.FromArgb(0, 255 - gg, gg);
            }

            Color lc = Color.Blue;
            lc = Color.FromArgb(192, lc);
            foreach (var l in Graph.GetLinks())
            {
                l.color = lc;
                if (ShowTextOnLinks)
                {
                    l.text = (l as WikiVisLink).rel.ToString("0.0%");
                }
                else
                {
                    l.text = null;
                }
            }

            if (ColorCurrentPath)
            {
                for (int i = 0; i < Path.Length; i++)
                {
                    Graph.GetNode(Path[i].title).color = Color.Salmon;

                    if (i<Path.Length-1)
                        Graph.GetLink(Graph.GetNode(Path[i].title), Graph.GetNode(Path[i+1].title)).color = Color.Salmon;
                }
            }
        }


        protected class Candidate
        {
            public Article article;
            public Article destination;

            public float G;
            public float H;
            public float f;

            public void Calc()
            {
                H = (1 - Relatedness.Get(article.title, destination.title));
                if (H == 1)
                    H = 1000;


                f = G + H;
            }


            private Candidate _parent = null;

            public Candidate parent
            {
                set
                {
                    _parent = value;
                    if (value == null)
                    {
                        G = 0;
                    }
                    else
                    {
                        G = _parent.G + 1 - Relatedness.Get(article.title, _parent.article.title);
                        destination = parent.destination;
                    }
                    Calc();
                }
                get
                {
                    return _parent;
                }
            }

            internal void UpdateParentIfBetter(Candidate newparent)
            {
                if (_parent != null)
                {
                    if (_parent.G + 1 - Relatedness.Get(article.title, newparent.article.title) < G)
                    {
                        parent = newparent;
                    }
                }
            }
        }       

    }
}
